const userCenterToast = Swal.mixin({
    toast: true,
    position: 'center',
    background: '#ffffe1',
    showConfirmButton: false,
    backdrop: false,
    timer: 3000
});

function userCenterOnUploadImage() {

    var formData = new FormData($( "#uploadPic" )[0]);
    var ajaxUrl = "/api/uploadportrait";

    $.ajax({
        type: "POST",
        //dataType: "text",
        url: ajaxUrl,
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {
            var json = JSON.parse(response);
            if (json.result == 200) {
                // var path = json.path.replace('src\\main\\resources\\static\\', '')
                // $('#picture-portrait-preview').attr('src', path);
            }
            else {
                console.log(json.description);
            }
        },
        error: function(data) {
            alert("error:"+data.responseText);
        }
    });
    return false;
}

function userCenterOnImageChanged(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            // image must be 128 x 128
            var image = new Image();
            image.onload = function() {
                var width = image.width;
                var height = image.height;

                if (width == 128 && height == 128) {
                    $('#picture-portrait-preview')
                        .attr('src', e.target.result)
                        .width(128)
                        .height(128);
                }
                else {
                    var f = $('#input-file-path').get(0);
                    if(f.value){
                        try{
                            f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
                        }catch(err){
                        }
                        // if(f.value){ //for IE5 ~ IE10
                        //     var form = document.createElement('form'), ref = f.nextSibling;
                        //     form.appendChild(f);
                        //     form.reset();
                        //     ref.parentNode.insertBefore(f,ref);
                        // }
                    }


                    Swal.fire('头像图片必须是128x128的。');
                }
            }
            image.src = reader.result;
        };
        reader.readAsDataURL(input.files[0]);
    }
}

function userCenterOnModifyPortraitClick(target) {
    $('#stepto-modify-portrait').css('display', 'block');
}

function userCenterOnCancelCollectClick(target) {
    var fictionId = $(target).attr('fictionId');
    var parentHandle = $(target).parent();

    $.ajax({
        type: 'post',
        async: true,
        data: {"id": fictionId},
        url: document.location.origin + '/api/collect',
        dataType: 'text',
        error: function() {

        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                parentHandle.remove();

                var contentListHandle = $('#list-of-content');
                if (contentListHandle.children().length === 0) {
                    window.location.reload(true);
                }
            }
            else {
                console.log(json.description);
            }
        }
    });
}

function userCenterOnCancelSelectCollectClick() {
    var contentListHandle = $('#list-of-content');
    var children = contentListHandle.children();

    var idArray = [], handleArray = [];
    for (var i = 0; i < children.length; ++i) {
        var buttonHandle = $(children[i]).children('button');
        var fictionId = buttonHandle.attr('fictionId');

        var divHandle = $(children[i]).children('.icheck-primary');
        var checkHandle = $(divHandle).children('input');
        if(checkHandle.prop('checked')) {
            idArray.push(fictionId);
            handleArray.push(buttonHandle.parent());
        }
    }

    if (idArray.length > 0) {
        $.ajax({
            type: 'post',
            async: true,
            data: {"idarray": idArray},
            url: document.location.origin + '/api/uncollectall',
            dataType: 'text',
            error: function() {

            },
            success: function(data) {
                var json = JSON.parse(data);

                if (json.result == 200) {
                    for (var i = 0; i < handleArray.length; ++i) {
                        handleArray[i].remove();
                    }

                    //如果没有任何的收藏，则连content list一起remove
                    if (contentListHandle.children().length === 0) {
                        window.location.reload(true);
                    }
                }
                else {
                    console.log(json.description);
                }
            }
        });
    }
}

function userCenterOnCheckAllChange(target) {
    var contentListHandle = $('#list-of-content');
    var children = contentListHandle.children();

    var checked = $(target).prop('checked');

    for (var i = 0; i < children.length; ++i) {
        var divHandle = $(children[i]).children('.icheck-primary');
        var checkHandle = $(divHandle).children('input');
        checkHandle.prop('checked', checked);
        if (checked) {
            $(children[i]).addClass('done');
        }
        else {
            $(children[i]).removeClass('done');
        }
    }

    userCenterOnCheckChange();
}

function userCenterOnCheckChange() {
    var contentListHandle = $('#list-of-content');
    var children = contentListHandle.children();

    var cancelAllButtonHandle = $('#cancel-all-button');
    var checkSelectAllHandle = $('#checkbox-select-all');

    var checkCount = 0;
    for (var i = 0; i < children.length; ++i) {
        var divHandle = $(children[i]).children('.icheck-primary');
        var checkHandle = $(divHandle).children('input');

        if (checkHandle.prop('checked')) {
            checkCount++;
        }
    }

    if (checkCount === children.length) {
        checkSelectAllHandle.prop('checked', true);
    }
    else {
        checkSelectAllHandle.prop('checked', false);
    }

    if (checkCount === 0) {
        cancelAllButtonHandle.prop('disabled', true);
    }
    else {
        cancelAllButtonHandle.prop('disabled', false);
    }
}

function useCenterOnCloseToast() {
    $('#toastsContainerTopRight').css('display', 'none');
}

function useCenterOnBindChangeEmail(target) {
    $('#change-email-container').css('display', 'block');
    $(target).text('更新中...');
}

function useCenterOnSendVerifyEmail(target) {
    var email = $('#email-verify-input').val();
    if (validateEmail(email)) {
        $(target).text('邮件验证中...');
        $(target).prop('disabled', true);
        $('#email-verify-input').prop('disabled', true);
        $('#change-email-container').css('display', 'none');

        $.ajax({
            type: 'post',
            async: true,
            data: {"email": email, "type": 1},
            url: document.location.origin + '/api/mailsend',
            dataType: 'text',
            error: function() {

            },
            success: function(data) {
                var json = JSON.parse(data);

                if (json.result == 200) {
                    userCenterToast.fire({
                        type: 'success',
                        title: '确认邮件已经发出，请到您的邮箱确认，然后刷新浏览器。',
                    });
                }
                else {
                    userCenterToast.fire({
                        type: 'error',
                        title: json.description,
                    });
                }

                $(target).text('发送验证邮件');
                $(target).prop('disabled', false);
                $('#email-verify-input').prop('disabled', false);
                $('#change-update-email-button').text("绑定/更换");
            }
        });
    }
    else {
        userCenterToast.fire({
            type: 'error',
            title: "<span style='color:black;'>邮箱格式不正确</span>",
        });
    }
}

function userCenterAccountOnModifyPassword(target) {
    $('#password-modify-area').css('display', 'block');
    $(target).css('display', 'none');
}

function userCenterAccountOnConfirmPassword(target) {
    var originalPassword = $('#original-password-input').val();
    var newPassword = $('#new-password-input').val();
    var newPassword2 = $('#new-password2-input').val();
    var uuid = $('#span-uuid').attr('value');

    if (originalPassword == '') {
        userCenterToast.fire({
            type: 'error',
            title: '请输入原来的密码',
        });
        return;
    }

    if (newPassword == '') {
        userCenterToast.fire({
            type: 'error',
            title: '新密码没有输入',
        });
        return;
    }

    if (newPassword2 != newPassword) {
        userCenterToast.fire({
            type: 'error',
            title: '两次新的密码不一致',
        });
        return;
    }

    var str = JSON.stringify({"password": originalPassword, "newpassword": newPassword, "uuid": uuid});
    var key = makeKey(16);
    var encrypted = CryptoJS.AES.encrypt(str, key).toString();

    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    key = encrypt.encrypt(key);

    $(target).prop('disabled', true);

    $.ajax({
        type: 'post',
        async: true,
        data: {"account": encrypted, "key": key},
        url: document.location.origin + '/api/modifypassword',
        dataType: 'text',
        error: function() {

        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                userCenterToast.fire({
                    type: 'success',
                    title: '密码更新成功。',
                });

                $(target).prop('disabled', false);
                $('#button-modify-password').css('display', 'block');
                $('#password-modify-area').css('display', 'none');
            }
            else {
                userCenterToast.fire({
                    type: 'error',
                    title: json.description,
                });
                $(target).prop('disabled', false);
            }
        }
    });
}

function userCenterNotifyOnClose(target) {
    var parent = $(target).parent();
    var id = parent.attr('value');

    $.ajax({
        type: 'post',
        async: true,
        data: {"id": id},
        url: document.location.origin + '/api/deletenotify',
        dataType: 'text',
        error: function() {

        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                parent.remove();
                window.location.reload(true);
            }
            else {
                userCenterToast.fire({
                    type: 'error',
                    title: json.description,
                });
            }
        }
    });
}

function useCenterNotifyOnClick(target) {
    var id = $(target).attr('value');

    $(target).children('span').fadeIn('slow', function() {
        $(target).removeClass('alert-info');
        $(target).addClass('alert-default-dark');

        $.ajax({
            type: 'post',
            async: true,
            data: {"id": id},
            url: document.location.origin + '/api/readnotify',
            dataType: 'text',
            error: function() {

            },
            success: function(data) {
                var json = JSON.parse(data);

                if (json.result == 200) {
                }
                else {
                }
            }
        });
    });
}

var userCenterOldNick = '';
function userCenterOnModifyNickClick(target) {
    $('#button-modify-nick').css('display', 'none');
    $('#button-finish-nick').css('display', 'block');
    $('#button-abandon-nick').css('display', 'block');
    $('#input-of-nick').removeAttr('readonly');

    userCenterOldNick = $('#input-of-nick').val();
}

function userCenterOnFinishNickClick(target) {
    $('#button-abandon-nick').css('display', 'none');
    $('#button-finish-nick').css('display', 'none');
    $('#button-modify-nick').css('display', 'block');
    $('#input-of-nick').attr('readonly', 'readonly');

    var newNick = $('#input-of-nick').val();
    if (newNick == null || newNick.trim() == '') {
        return;
    }

    var uuid = $('#span-uuid').attr('value');
    if (uuid == null || uuid.trim() == '') {
        return;
    }

    if (newNick == userCenterOldNick) {
        return;
    }

    $.ajax({
        type: 'post',
        async: true,
        data: {"oldNick": userCenterOldNick, "newNick": newNick, "uuid": uuid},
        url: document.location.origin + '/api/modifynick',
        dataType: 'text',
        error: function() {

        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                userCenterToast.fire({
                    type: 'success',
                    title: '修改昵称成功',
                });
            }
            else {
                userCenterToast.fire({
                    type: 'error',
                    title: json.description,
                });
            }
        }
    });
}

function userCenterOnAbandonNickClick(target) {
    $('#button-abandon-nick').css('display', 'none');
    $('#button-finish-nick').css('display', 'none');
    $('#button-modify-nick').css('display', 'block');
    $('#input-of-nick').attr('readonly', 'readonly');
}

$(document).ready(function() {
    Tipped.create('#nick-icon-circle', "昵称在全站是唯一的。通过邮箱注册会自动分配，您可以自由修改。", {skin:'blue'});

    $('#button-modify-nick').css('display', 'block');
    $('#button-finish-nick').css('display', 'none');
    $('#button-abandon-nick').css('display', 'none');
});